/*
 * 文件名：SearchUtil.java	 
 * 时     间：下午7:27:13
 * 作     者：Administrator       
 * 版     权： 2012-2022 湖南智软网络科技, 公司保留所有权利.
 * 联     系：http://www.073586.com/
 */
package com.zbc.lucene.util;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import com.cz073586.tools.util.Log4jUtil;
import com.index.entity.Page;
import com.index.util.LucenePage;

/**
 * 类描述:这里是类描述
 * 
 * @ClassName: SearchUtil
 * @author Administrator
 * @date 2016年8月7日 下午7:27:13
 */
public class SearchUtil
{
	private static final Log4jUtil LOG = Log4jUtil.getLog4j(SearchUtil.class);
	
	private static Directory dir;
	private static IndexReader reader;
	
	private SearchUtil()
	{
	}
	
	public static void closeReader()
	{
		if (null != reader)
		{
			try
			{
				reader.close();
				dir.close();
				LOG.info("close IndexReader" + reader);
			} catch (IOException e)
			{
				LOG.info("close IndexReader caught a " + e.getClass()
						+ "\n with message: " + e.getMessage());
			}
		}
	}
	
	public static <T> Page<Document> pageQueryIndex(String path,
			LucenePage<T> carParkInPage)
	{
		//TODO 检查参数为空的异常
		int pageSize = carParkInPage.getPageSize();
		int currentPage = carParkInPage.getCurrentPage();
		Page<Document> page = new Page<Document>(currentPage, pageSize);
		
		try
		{
			dir = FSDirectory.open(Paths.get(path));
			reader = DirectoryReader.open(dir);
			IndexSearcher searcher = new IndexSearcher(reader);
			Analyzer analyzer = IndexUtil.getAnalyzer();
			
			QueryParser parser = new QueryParser(FieldEnum.CONTENTS.name(),
					analyzer);
			
			Query query = parser.parse(carParkInPage.getCarNo());
			// Query query = new FuzzyQuery(new Term(FieldEnum.CONTENTS.name(),
			// carParkInPage.getCarNo()));
			// Query query = new RegexpQuery(new Term(FieldEnum.CONTENTS.name(),
			// carParkInPage.getCarNo()));
			LOG.info("Searching for: "
					+ query.toString(carParkInPage.getCarNo()));
			
			Date start = new Date();
			
			TopDocs results = searcher.search(query, currentPage * pageSize);
			ScoreDoc[] hits = results.scoreDocs;
			
			Date endDate = new Date();
			LOG.info("Time: " + (endDate.getTime() - start.getTime()) + "ms");
			int numTotalHits = results.totalHits;
			LOG.info(numTotalHits + " total matching documents");
			
			// 查询起始记录位置
			int begin = pageSize * (currentPage - 1);
			// 查询终止记录位置
			int end = Math.min(begin + pageSize, hits.length);
			
			// 迭代输出结果
			List<String> carInUuidList = new ArrayList<String>();
			for (int i = begin; i < end; i++)
			{
				Document hitDoc = searcher.doc(hits[i].doc);
				carInUuidList.add(hitDoc.get(FieldEnum.STRING_FIELD.name()));
			}
			page.setList(carInUuidList);
			page.setTotalRecord(hits.length);
			
		} catch (Exception e)
		{
			LOG.error("{}", e);
		} finally
		{
			closeReader();
		}
		return page;
	}
	
}
